package xio.ccf_201609;

import java.util.Scanner;

/**
 * ccf 201609-2 火车购票 100分
 * Created by Xio on 2017/10/19 0019.
 */
public class TicketsBooking {

    public static void main(String[] args) {

        TicketsBookingSystem bookingSystem = new TicketsBookingSystem(20, 5);

        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt(); //操作数
        int[] src = new int[m]; //订票数
        for (int i = 0; i < m; i++) {
            src[i] = sc.nextInt();
        }

        for (int a : src) {
            int[] tickets = bookingSystem.buyTickets(a);
            for (int ticket : tickets) {
                System.out.print(ticket + " ");
            }
            System.out.printf("\n");
        }
    }

    static class TicketsBookingSystem{
        boolean[][] seats;  //记录座位是否已被订购
        int[] seatsPerRow;  // 记录每排已购座位数
        int rowCount;
        int columnCount;

        public TicketsBookingSystem(int rowCount, int columnCount) {
            this.rowCount = rowCount;
            this.columnCount = columnCount;
            seats = new boolean[rowCount + 1][columnCount + 1];
            seatsPerRow = new int[rowCount + 1];
        }

        /**
         * 购票
         * 流程: 先寻找符合订票数的连座的行，有，则就在这行分配座位号 否则遍历所有seats数组 分配可订购座位
         * @param count 订票数
         * @return 系统分配的座位号
         */
        public int[] buyTickets(int count) {
            int[] result = new int[count];
            int index = 0;
            int row = findEnoughSeatsRow(count);
            if (row != -1) {
                seatsPerRow[row] =seatsPerRow[row]+ count;
                for (int i = 1; i < seats[row].length; i++) {
                    if (!seats[row][i] && index <= count - 1) {
                        result[index++] = (row - 1) * columnCount + i;
                        seats[row][i] = true;
                    }
                }
                return result;
            }
            for (int i = 1; i < seats.length; i++) {
                if (seatsPerRow[i] == columnCount) continue; //这行订满了 直接略过这行
                for (int j = 1; j < seats[i].length; j++) {
                    if (!seats[i][j] && index <= count -1) {
                        result[index++] = (i - 1) * columnCount + j;
                    }
                }
            }
            return result;
        }

        /**
         * 寻找是否还有符合订票数量的相邻的座位的行，有，则返回该行 否则返回-1
         * @param count
         * @return
         */
        private int findEnoughSeatsRow(int count) {
            for (int i = 1; i < seatsPerRow.length; i++) {
                if (columnCount - seatsPerRow[i] >= count) {
                    return i;
                }
            }
            return -1;
        }
    }

}
